<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of task_obj
 *
 * @author Juraj
 */
class task_obj {

    public function addTask($in_data) {
        if (empty($in_data)) {
            return new error_obj('addTask -> empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $result = $db_obj->insert($GLOBALS['tb_tasks'], $in_data);
        if (error_obj::isError($result))
            return $result;
        else
            return $db_obj->lastInsertedId();
    }

    public function editTask($in_data, $id) {
        $id = (int) $id;
        if (empty($id)) {
            return new error_obj('empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $keys = array('taskId' => $id);
        return $db_obj->update($GLOBALS['tb_tasks'], $in_data, $keys);
    }

    public function addOrderOfGoods($in_data, $taskId=0) {
        if (empty($in_data)) {
            return new error_obj('addOrderOfGoods -> empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $keys = array('taskId' => $taskId);
        $result = $db_obj->insertUpdate($GLOBALS['tb_task_type_order_of_goods'], $in_data, $keys);
        return $result;
    }

    public function getOrderOfGoods($taskId) {
        $taskId = (int) $taskId;
        if (empty($taskId)) {
            return new error_obj('getOrderOfGoods -> empty $taskId', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $sql = "SELECT * FROM " . $GLOBALS['tb_task_type_order_of_goods'] . " WHERE taskId='" . $taskId . "'";

        return $db_obj->getRow($sql);
    }

    public function addOperationWithUser($in_data, $taskId = 0) {
        if (empty($in_data)) {
            return new error_obj('addOperationWithUser -> empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $keys = array('taskId' => $taskId);
        $result = $db_obj->insertUpdate($GLOBALS['tb_task_type_operation_with_user'], $in_data, $keys);
        return $result;
    }

    public function getOperationWithUser($taskId) {
        $taskId = (int) $taskId;
        if (empty($taskId)) {
            return new error_obj('getOperationWithUser -> empty $taskId', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $sql = "SELECT * FROM " . $GLOBALS['tb_task_type_operation_with_user'] . " WHERE taskId='" . $taskId . "'";

        return $db_obj->getRow($sql);
    }

    public function getOperationsWithUser($filter = array(), $order = '', $limit = '', $what = '*') {
        $db_obj = new db_obj();
        if ($order != '')
            $order = ' ORDER BY ' . $order;
        if ($limit != '')
            $limit = ' LIMIT ' . $limit;

        $where = 'WHERE 1=1';

        foreach ($filter as $key => $value) {
            $where .= " AND " . $key . "='" . $value . "'";
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_task_type_operation_with_user'] . " $where $order $limit";
        base_obj::debug('getOperationsWithUser sql', $sql);

        return $db_obj->getAll($sql);
    }

    public function getTaskTypes() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_records'] . " WHERE task=1 ORDER BY Id";
        base_obj::debug("getAllTaskTypes sql", $sql);

        return $db_obj->getAll($sql);
    }

    public function getTaskType($id) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_records'] . " WHERE Id='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function getTaskTypeOfProblems() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_type_of_problems'] . " ORDER BY id";
        base_obj::debug("getTaskTypeOfProblems sql", $sql);


        return $db_obj->getAll($sql);
    }

    public function getTaskTypeOfProblem($id) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_type_of_problems'] . " WHERE id='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function getTaskTypeOfOperations() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_type_of_operations'] . " ORDER BY id";
        base_obj::debug("getTaskTypeOfOperations sql", $sql);


        return $db_obj->getAll($sql);
    }

    public function getTaskStatuses($order = 'id_stav') {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_statuses'] . " ORDER BY $order";
        base_obj::debug("getAllTaskStatuses sql", $sql);


        return $db_obj->getAll($sql);
    }

    public function getTaskStatus($id) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_statuses'] . " WHERE id_stav='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function getTaskPriorities() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_priorities'] . " ORDER BY Priorita";
        base_obj::debug("getAllTaskPriorities sql", $sql);


        return $db_obj->getAll($sql);
    }

    public function getTaskPriority($id) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $sql = "SELECT * FROM " . $GLOBALS['tb_task_priorities'] . " WHERE id='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function checkAdd_task($check_data) {
        $result = array();
        foreach ($check_data as $key => $value) {
            switch ($key) {
                case 'client':
                    if ($value == -1)
                        $result[] = 'client';
                    break;
                case 'deadline':
                    if (empty($value))
                        $result[] = 'deadline';
                    break;
                case 'description':
                    if (empty($value))
                        $result[] = 'description';
                    break;
                case 'priority':
                    if ($value == -1)
                        $result[] = 'priority';
                    break;
                case 'responsible':
                    if ($value == -1)
                        $result[] = 'responsible';
                    break;
                case 'start':
                    if ((date("d/m/Y") > $value))
                        $result[] = 'created';
                    break;
                case 'status':
                    if (!isset($value) || (empty($value)))
                        $result[] = 'status';
                    break;
                case 'title':
                    if (empty($value))
                        $result[] = 'title';
                    break;
                case 'type':
                    if (empty($value))
                        $result[] = 'type';
                    break;
                case 'duration':
                    $value = (double) $value;
                    if ($value <= 0)
                        $result[] = 'duration';
                    break;
            }
        }
        return $result;
    }

    public function getListOfTasks($filter = array(), $order = array(), $limit = '', $what = '*') {
        $db_obj = new db_obj();

        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)) {
            $second_order = '';
            if (!empty($order['second']))
                $second_order = " , " . $order['second'];
            if (!empty($order['table'])) {
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' . $order['orderBy'] . ' ' . $order['order'] . $second_order;
                $connector = 'AND ' . $GLOBALS['tb_tasks'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'] . $second_order;
            }
        }

        if (strpos($what, 'COUNT') === false) {
            $what = $GLOBALS['tb_tasks'] . '.' . $what;
        }

        if ($limit != '')
            $limit = ' LIMIT ' . $limit;

        $where = 'WHERE 1=1';

        foreach ($filter as $key => $value) {
            if ($key == 'clients') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= $GLOBALS['tb_tasks'] . ".client='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } else {
                if ($key == 'responsible_or_worker')
                    $where .= " AND (responsible='" . $value . "' OR worker='" . $value . "')";
                elseif ($key == 'client')
                    $where .= " AND " . $GLOBALS['tb_tasks'] . ".client='" . $value . "'";
                elseif ($key == 'updated_month')
                    $where .= " AND DATE_FORMAT(updated,'%c')='" . $value . "'";
                elseif ($key == 'updated_year')
                    $where .= " AND DATE_FORMAT(updated,'%Y')='" . $value . "'";
                else
                    $where .= " AND " . $key . "='" . $value . "'";
            }
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_tasks'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug('getListOfTasks sql', $sql);

        return $db_obj->getAll($sql);
    }

    public function getListOfTasksByFulltext($fulltext, $filter = array(), $order = array(), $limit = '', $what = '*') {
        $where = '';
        $db_obj = new db_obj();

        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)) {
            $second_order = '';
            if (!empty($order['second']))
                $second_order = " , " . $order['second'];
            if (!empty($order['table'])) {
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' . $order['orderBy'] . ' ' . $order['order'] . $second_order;
                $connector = 'AND ' . $GLOBALS['tb_tasks'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'] . $second_order;
            }
        }

        if (!empty($fulltext)) {
            $fulltext = strip_tags(trim($fulltext));

            $fulltext = explode(" ", $fulltext);
            $fulltextResults = array();
            foreach ($fulltext as $key => $word) {
                $sql = "SELECT " . $GLOBALS['tb_tasks'] . ".taskId 
                    FROM " . $GLOBALS['tb_tasks'] . ",
                         " . $GLOBALS['tb_clients'] . ",
                         " . $GLOBALS['tb_users'] . ",
                         " . $GLOBALS['tb_task_phorum'] . "    
                    WHERE 
                    " . $GLOBALS['tb_tasks'] . ".client = " . $GLOBALS['tb_clients'] . ".klient_id AND (
                    " . $GLOBALS['tb_tasks'] . ".worker = " . $GLOBALS['tb_users'] . ".users_id OR    
                    " . $GLOBALS['tb_tasks'] . ".responsible = " . $GLOBALS['tb_users'] . ".users_id OR    
                    " . $GLOBALS['tb_tasks'] . ".creator = " . $GLOBALS['tb_users'] . ".users_id OR    
                    " . $GLOBALS['tb_tasks'] . ".updater = " . $GLOBALS['tb_users'] . ".users_id ) AND    
                    " . $GLOBALS['tb_task_phorum'] . ".task_id = " . $GLOBALS['tb_tasks'] . ".taskId AND (
                    " . $GLOBALS['tb_tasks'] . ".title LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".name LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".surname LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_task_phorum'] . ".text LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_clients'] . ".name LIKE '%" . $word . "%'
                    )";
                $fulltextResults[] = array_unique($db_obj->getCol($sql));
            }
            if (isset($fulltextResults[0]) && !empty($fulltextResults[0])) {
                $temp = $fulltextResults[0];
                foreach ($fulltextResults as $key => $array) {
                    $temp = array_intersect($temp, $array);
                }
                if (!empty($temp)) {
                    $where .= 'WHERE (';
                    foreach ($temp as $id) {
                        $where .= "taskId='" . $id . "' OR ";
                    }
                    $where = substr($where, 0, $length - 4);
                    $where .= ')';
                } else {
                    $where .= 'WHERE 1=2';
                }
            } else {
                $where .= 'WHERE 1=2';
            }
        } else {
            $where .= 'WHERE 1=1';
        }

        if ($order != '')
            $order = ' ORDER BY ' . $order;
        if ($limit != '')
            $limit = ' LIMIT ' . $limit;
        if (strpos($what, 'COUNT') === false) {
            $what = $GLOBALS['tb_tasks'] . '.' . $what;
        }
        foreach ($filter as $key => $value) {
            if ($key == 'clients') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= $GLOBALS['tb_tasks'] . ".client='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } else {
                if ($key == 'responsible_or_worker')
                    $where .= " AND (responsible='" . $value . "' OR worker='" . $value . "')";
                elseif ($key == 'client')
                    $where .= " AND " . $GLOBALS['tb_tasks'] . ".client='" . $value . "'";
                else
                    $where .= " AND " . $key . "='" . $value . "'";
            }
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_tasks'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug('getListOfTasks sql', $sql);

        return $db_obj->getAll($sql);
    }

    public function getTaskById($id) {
        $id = (int) $id;
        if (empty($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_tasks'] . " WHERE taskId='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function deleteTask($id) {
        $id = (int) $id;
        if (empty($id)) {
            return new error_obj('empty id', __CLASS__, __FUNCTION__);
        }

        $db_obj = new db_obj();

        $sql = "DELETE FROM " . $GLOBALS['tb_tasks'] . " WHERE taskId='" . $id . "'";
        return $db_obj->query($sql);
    }

    public function send_notification($taskId, $task, $action = 'add', $originalTask = array(), $alls = false) {
        $notify_obj = new notify_obj();
        $client_obj = new client_obj();
        $user_obj = new user_obj();

        //base_obj::debug("sned_notificaition", $task);
        //base_obj::debug("sned_notificaition", $originalTask);

        $recipients = array();
        if ($alls) {
            $recipients[1] = 1; // Ondrej Veliky
            $recipients[2] = 2; // Andrej Sec
            $recipients[$task['responsible']] = $task['responsible'];
            if ($task['worker'] != -1)
                $recipients[$task['worker']] = $task['worker'];
        } else {
            $recipients[$task['responsible']] = $task['responsible'];
        }
        $subject_status = $this->getTaskStatus($task['status']);
        $subject_client = $client_obj->getClient($task['client'], array("name"));

        switch ($action) {
            case 'add':
                $updater = $task['creator'];
                $subject_descr = $task['title'];
                $task_info = $this->newTaskNotification($taskId);
                break;
            case 'edit':
                $updater = $task['updater'];
                $subject_descr = $task['title'];
                $task_info = $this->editTaskNotification($taskId, $originalTask, $task['post']);
                break;
        }

        if ($alls && isset($recipients[$updater])) {
            unset($recipients[$updater]);
        }
        $recipients_emails = array();
        foreach ($recipients as $userId) {
            $email = $user_obj->getUserById($userId, array('email, notify'));
            if (!error_obj::isError($email))
                if ($userId == $task['responsible']) {
                    if (!empty($email['notify']))
                        $recipients_emails[] = $email['email'];
                } else {
                    $recipients_emails[] = $email['email'];
                }
        }
        //base_obj::debug("recipients", $recipients_emails);

        $subject = "CM:" . $subject_status['stav'] . ":" . $subject_client['name'] . ":" . $subject_descr;
        $message = 'Task: <a href="' . WWW . '?input=edit_task&task=' . $taskId . '">' . $task['title'] . '</a>';
        $sender = $user_obj->getUserById($updater, array('name', 'surname', 'email'));

        $send_result = $notify_obj->send($recipients_emails, $message . $task_info, $subject, array("email" => $sender['email'], "name" => $sender['name'] . " " . $sender['surname']));
        if (error_obj::isError($send_result))
            return $send_result;
        return true;
    }
    
    public function compareTasks($originalTask, $updatedTask) {
        $out_data = array();
        $user_obj = new user_obj();
        $client_obj = new client_obj();
        foreach ($updatedTask as $key => $value) {
            $not_compare = array('taskId', 'added', 'creator', 'updated', 'updater', 'file', 'post', 'problem_type', 'consult', 'rate');
            if (!is_numeric($key) && !in_array($key, $not_compare)) {
                if (trim($value) != trim($originalTask[$key])) {
                    switch ($key) {
                        case 'created':
                            $originalValue = base_obj::convertDateTo($originalTask[$key], 'dd/mm/yyyy', 'date');
                            $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                            break;
                        case 'client':
                            $originalValue = $client_obj->getClient($originalTask[$key], array("name"));
                            $originalValue = $originalValue['name'];
                            $newValue = $client_obj->getClient($value, array("name"));
                            $newValue = $newValue['name'];
                            break;
                        case 'worker':
                            if ($originalTask[$key] != -1) {
                                $originalValue = $user_obj->getUserById($originalTask[$key], array("name", "surname"));
                                $originalValue = $originalValue['name'] . ' ' . $originalValue['surname'];
                            } else {
                                $originalValue = '-';
                            }
                            if ($value != -1) {
                                $newValue = $user_obj->getUserById($value, array("name", "surname"));
                                $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                            } else {
                                $newValue = '-';
                            }
                            break;
                        case 'responsible':
                            $originalValue = $user_obj->getUserById($originalTask[$key], array("name", "surname"));
                            $originalValue = $originalValue['name'] . ' ' . $originalValue['surname'];
                            $newValue = $user_obj->getUserById($value, array("name", "surname"));
                            $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                            break;
                        case 'deadline':
                            $originalValue = base_obj::convertDateTo($originalTask[$key], 'dd/mm/yyyy', 'date');
                            if ($originalValue == MAX_DEADLINE)
                                $originalValue = '-';
                            $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                            if ($newValue == MAX_DEADLINE)
                                $newValue = '-';
                            break;
                        case 'type':
                            $originalValue = $this->getTaskType($originalTask[$key]);
                            $originalValue = $originalValue['type_of_record'];
                            $newValue = $this->getTaskType($value);
                            $newValue = $newValue['type_of_record'];
                            break;
                        case 'priority':
                            $originalValue = $this->getTaskPriority($originalTask[$key]);
                            $originalValue = $originalValue['Popis'];
                            $newValue = $this->getTaskPriority($value);
                            $newValue = $newValue['Popis'];
                            break;
                        case 'status':
                            $originalValue = $this->getTaskStatus($originalTask[$key]);
                            $originalValue = $originalValue['stav'];
                            $newValue = $this->getTaskStatus($value);
                            $newValue = $newValue['stav'];
                            break;
                        default:
                            $originalValue = $originalTask[$key];
                            $newValue = $value;
                            break;
                    }
                    $out_data[$key] = array(
                        'original' => $originalValue,
                        'new' => $newValue
                    );
                }
            }
        }
        return $out_data;
    }

    private function newTaskNotification($taskId) {

        $user_obj = new user_obj();
        $client_obj = new client_obj();
        $task_phorum_obj = new task_phorum_obj();

        $task_info = $this->getTaskById($taskId);
        if (error_obj::isError($task_info))
            return '';

        //base_obj::debug("new task notify", $task_info);

        $message = '<table>';

        foreach ($task_info as $key => $value) {
            $not_compare = array('taskId', 'created', 'type', 'priority', 'status', 'file', 'added', 'creator', 'updated', 'updater', 'problem_type', 'consult', 'rate');
            if (!is_numeric($key) && !in_array($key, $not_compare)) {
                switch ($key) {
                    case 'created':
                        $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                        break;
                    case 'client':
                        $newValue = $client_obj->getClient($value, array("name"));
                        $newValue = $newValue['name'];
                        break;
                    case 'worker':
                        if ($value != -1) {
                            $newValue = $user_obj->getUserById($value, array("name", "surname"));
                            $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                        } else {
                            $newValue = '-';
                        }
                        break;
                    case 'responsible':
                        $newValue = $user_obj->getUserById($value, array("name", "surname"));
                        $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                        break;
                    case 'deadline':
                        $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                        if ($newValue == MAX_DEADLINE)
                            $newValue = '-';
                        break;
                    default:
                        $newValue = $value;
                        break;
                }
                $message .= '<tr>';
                $message .= '<td>New ' . $key . ':</td>';
                $message .= '<td>' . $newValue . '</td>';
                $message .= '</tr>';
            }
        }

        $filter = array(
            'task_id' => $taskId
        );
        $post = $task_phorum_obj->getPostsInPhorum($filter, '', '0,1', array('text'));
        base_obj::debug('a co post', $post);
        if (!error_obj::isError($post) && !empty($post[0]['text'])) {
            $message .= '<tr>';
            $message .= '<td>Description:</td>';
            $message .= '<td>' . htmlspecialchars_decode($post[0]['text']) . '</td>';
            $message .= '</tr>';
        }

        $message .= '</table>';

        return $message;
    }

    private function editTaskNotification($taskId, $originalTask = array(), $newPost = '') {

        $user_obj = new user_obj();
        $client_obj = new client_obj();

        $task_info = $this->getTaskById($taskId);
        if (error_obj::isError($task_info))
            return '';

        //base_obj::debug("edit task notify", $task_info);
        //base_obj::debug("edit task notify", $originalTask);

        $message = '<table>';

        foreach ($task_info as $key => $value) {
            $not_compare = array('taskId', 'added', 'creator', 'updated', 'updater', 'file', 'post', 'problem_type', 'consult', 'rate');
            if (!is_numeric($key) && !in_array($key, $not_compare)) {
                if (trim($value) != trim($originalTask[$key])) {
                    switch ($key) {
                        case 'created':
                            $originalValue = base_obj::convertDateTo($originalTask[$key], 'dd/mm/yyyy', 'date');
                            $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                            break;
                        case 'client':
                            $originalValue = $client_obj->getClient($originalTask[$key], array("name"));
                            $originalValue = $originalValue['name'];
                            $newValue = $client_obj->getClient($value, array("name"));
                            $newValue = $newValue['name'];
                            break;
                        case 'worker':
                            if ($originalTask[$key] != -1) {
                                $originalValue = $user_obj->getUserById($originalTask[$key], array("name", "surname"));
                                $originalValue = $originalValue['name'] . ' ' . $originalValue['surname'];
                            } else {
                                $originalValue = '-';
                            }
                            if ($value != -1) {
                                $newValue = $user_obj->getUserById($value, array("name", "surname"));
                                $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                            } else {
                                $newValue = '-';
                            }
                            break;
                        case 'responsible':
                            $originalValue = $user_obj->getUserById($originalTask[$key], array("name", "surname"));
                            $originalValue = $originalValue['name'] . ' ' . $originalValue['surname'];
                            $newValue = $user_obj->getUserById($value, array("name", "surname"));
                            $newValue = $newValue['name'] . ' ' . $newValue['surname'];
                            break;
                        case 'deadline':
                            $originalValue = base_obj::convertDateTo($originalTask[$key], 'dd/mm/yyyy', 'date');
                            if ($originalValue == MAX_DEADLINE)
                                $originalValue = '-';
                            $newValue = base_obj::convertDateTo($value, 'dd/mm/yyyy', 'date');
                            if ($newValue == MAX_DEADLINE)
                                $newValue = '-';
                            break;
                        case 'type':
                            $originalValue = $this->getTaskType($originalTask[$key]);
                            $originalValue = $originalValue['type_of_record'];
                            $newValue = $this->getTaskType($value);
                            $newValue = $newValue['type_of_record'];
                            break;
                        case 'priority':
                            $originalValue = $this->getTaskPriority($originalTask[$key]);
                            $originalValue = $originalValue['Popis'];
                            $newValue = $this->getTaskPriority($value);
                            $newValue = $newValue['Popis'];
                            break;
                        case 'status':
                            $originalValue = $this->getTaskStatus($originalTask[$key]);
                            $originalValue = $originalValue['stav'];
                            $newValue = $this->getTaskStatus($value);
                            $newValue = $newValue['stav'];
                            break;
                        default:
                            $originalValue = $originalTask[$key];
                            $newValue = $value;
                            break;
                    }
                    $message .= '<tr>';
                    $message .= '<td>Original ' . $key . ':</td>';
                    $message .= '<td>' . $originalValue . '</td>';
                    $message .= '<td>New ' . $key . ':</td>';
                    $message .= '<td>' . $newValue . '</td>';
                    $message .= '</tr>';
                }
            }
        }

        if (!empty($newPost)) {
            $message .= '<tr>';
            $message .= '<td>New post:</td>';
            $message .= '<td colspan="3">' . $newPost . '</td>';
            $message .= '</tr>';
        }

        $message .= '</table>';

        return $message;


        //base_obj::debug("info about task", $message);
    }

    public function visibleTask($id) {
        if ($_SESSION['user']['profile']['userlevel'] != USER_TYPE_CLIENT)
            return true;

        $id = (int) $id;
        if (empty($id))
            return false;

        $task = $this->getTaskById($id);

        if (isset($_SESSION['user']['clients'][$task['client']]) && !empty($_SESSION['user']['clients'][$task['client']]))
            return true;

        return false;
    }

    public function getGoodTypes() {
        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_goods'] . " ORDER BY type ASC";
        base_obj::debug("getAllGoodTypes sql", $sql);

        return $db_obj->getAll($sql);
    }

    public function getGoodType($id) {
        $db_obj = new db_obj();
        $id = (int) $id;
        if (empty($id) || !is_numeric($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $sql = "SELECT * FROM " . $GLOBALS['tb_type_of_goods'] . " WHERE id='" . $id . "'";

        return $db_obj->getRow($sql);
    }

    public function updateTaskRate($taskId) {
        $id = (int) $taskId;
        if (empty($id))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $db_obj = new db_obj();

        $task = $this->getTaskById($id);
        if (error_obj::isError($task))
            return $task;
        elseif (empty($task))
            return new error_obj('empty task', __CLASS__, __FUNCTION__);

        if (empty($task['duration']))
            $rate = -1;
        else {
            $record_obj = new record_obj();
            
            $filter = array (
                'type' => 1,
                'taskId' => $id
            );
            $sum = 0;
            $records = $record_obj->getListOfRecords($filter, array(), '', 'amount');
            foreach ($records as $key => $record) {
                $sum += $record['amount'];
            }       
            
            $rate = $sum / $task['duration'] * 100;
            $rate = round($rate);
        }
        
        $in_data = array();
        $in_data['rate'] = $rate;
        return $this->editTask($in_data, $id);
        
    }
    
    public function getCountOfActiveMonths($start, $end) {
        if ($end == '0000-00-00 00:00:00')
            $end = time();
        else 
            $end = base_obj::convertDateTo($end, 'U', 'datetime');
        
        $start = base_obj::convertDateTo($start, 'U', 'datetime');
        
        $startM = date("m", $start);
        $startY = date("Y", $start);
        $endM = date("m", $end);
        $endY = date("Y", $end);
        
        if ($startY == $endY) {
            if ($startM > $endM)
                return 0;
            else 
                return (($endM - $startM) + 1);
        } elseif ($startY < $endY) {
            return (($endM - $startM) + 12 + 1);
        } else {
            return 0;
        }
    }
    
    public function getArrayOfMonths($start, $count) {
        $start = base_obj::convertDateTo($start, 'U', 'datetime');
        
        $startM = date("m", $start);
        $startY = date("Y", $start);
        
        $months = array ();
        
        for ($i = 0; $i < $count; $i ++) {
            $temp = mktime(12, 0, 0, $startM + $i, 1, $startY);
            $months[date("m", $temp).'_'.date("Y", $temp)] = array(date("m", $temp), date("Y", $temp));
        }
        
        return $months;
    }
    
    public function getLastEmailProcessing() {
        $db_obj = new db_obj();
        $sql = "SELECT last_timestamp FROM " . $GLOBALS['tb_last_email_processing'] . " ORDER BY last_timestamp DESC LIMIT 1";

        return $db_obj->getOne($sql);
    }
    
    public function addLastEmailProcessing() {
        $db_obj = new db_obj();
        $in_data = array(
            'last_timestamp' => time()
        );
        
        $result = $db_obj->insert($GLOBALS['tb_last_email_processing'], $in_data);
        if (error_obj::isError($result))
            return $result;
        else
            return $db_obj->lastInsertedId();
    }
    
    public function getTaskByEmailHash($hash) {
        if (empty($hash))
            return new error_obj('empty id', __CLASS__, __FUNCTION__);

        $db_obj = new db_obj();

        $sql = "SELECT * FROM " . $GLOBALS['tb_tasks'] . " WHERE email_hash='" . $hash . "'";

        return $db_obj->getRow($sql);
    }

}

?>
